package org.linlinjava.litemall.admin.web;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.json.JSONObject;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.service.UserTokenHelper;
import org.linlinjava.litemall.admin.util.wxSendMessage;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;



@RestController
@RequestMapping("/admin/userAudit")
@Validated
public class AdminUserAuditController {
    private final Log logger = LogFactory.getLog(AdminGoodsController.class);


    @Autowired
    private LitemallUserAuditService userAuditService;

    @Autowired
    private wxSendMessage wxSendMessage;

    @Autowired
    private LitemallShopService shopService;

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private LitemallAdminService adminService;

    @Autowired
    private LitemallHerbService herbService;

    @Autowired
    private LitemallUserHerbAuthService userHerbAuthService;

    @Autowired
    private UserTokenHelper userTokenHelper;

    @Autowired
    private LitemallUserApproveService userApproveService;

    @Autowired
    private LitemallUserHerbApproveItemService userApproveItemService;


    /**
     * 查询用户信息审批
     *
     * @param sort
     * @param order
     * @return
     */
    @RequiresPermissions("admin:userAudit:list")
    @RequiresPermissionsDesc(menu = {"信息审批", "用户信息审批"}, button = "查询")
    @GetMapping("/list")
    public Object list(String approveStatus,String sort,
                       String order,
                       String userType,
                       String companyName,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit
                       ) {
        return ResponseUtil.okList(userAuditService.querySelective(approveStatus,userType,companyName,sort,order,page,limit));
    }

    /**
     * 查询药材
     *
     * @param userApproveId
     * @return
     */
    @RequiresPermissions("admin:userAudit:herbList")
    @RequiresPermissionsDesc(menu = {"信息审批", "用户信息审批"}, button = "查询药材")
    @GetMapping("/herbList")
    public Object herbList(String userApproveId) {
        List<String> list = new ArrayList<>();
        for (LitemallUserHerbApproveItem userHerbApprove:userAuditService.queryHerbList(userApproveId)) {
            list.add(0,userHerbApprove.getHerbGenericName());
        }
        return ResponseUtil.ok(list);
    }

    /**
     * 查询所有药材
     *
     * @param
     * @return
     */
    @RequiresPermissions("admin:userAudit:allHerbList")
    @RequiresPermissionsDesc(menu = {"信息审批", "用户信息审批"}, button = "查询所有药材")
    @GetMapping("/allHerbList")
    public Object allHerbList() {
        List<String> list = new ArrayList<>();
        for (LitemallHerb litemallHerb:herbService.selectByGenericName()) {
                if(!list.contains(litemallHerb.getGenericName())){
                    list.add(0,litemallHerb.getGenericName());
                }
            }
        return ResponseUtil.ok(list);
    }


    /**
     * 查询药材
     *
     * @param adminId
     * @return
     */
    @RequiresPermissions("admin:userAudit:queryRoleIds")
    @RequiresPermissionsDesc(menu = {"信息审批", "用户信息审批"}, button = "查询角色")
    @GetMapping("/queryRoleIds")
    public Object queryRoleIds(String adminId) {
        LitemallAdmin admin=adminService.findById(Integer.valueOf(adminId));
        return ResponseUtil.ok(admin.getRoleIds());
    }

    /**
     * 批准审批
     *
     * @param
     * @return
     */
    @RequiresPermissions("admin:userAudit:approvalUserAudit")
    @RequiresPermissionsDesc(menu = {"信息审批", "用户信息审批"}, button = "批准审批")
    @PostMapping("/approvalUserAudit")
    @Transactional
    public Object approvalUserAudit(@RequestBody LitemallUserApproveAndHreb userApprove) {
        LitemallUser user=userService.findById(userApprove.getUserId());
        LitemallShop ShopExample = new LitemallShop();

        //Shop
        if (StringUtils.isEmpty(user.getShopId())){//判断是否有商户id
            ShopExample.setId((int)System.currentTimeMillis());
            ShopExample.setContactName(userApprove.getContactName());
            ShopExample.setContactTel(userApprove.getContactTel());
            ShopExample.setContactAddress(userApprove.getContactAddress());
            ShopExample.setUserType(userApprove.getUserType());
            ShopExample.setCompanyName(userApprove.getCompanyName());
            ShopExample.setCompanyLogo(userApprove.getCompanyLogo());
            ShopExample.setCertificatesImage(userApprove.getCertificatesImage());
            ShopExample.setIdCard1Url(userApprove.getIdCard1Url());
            ShopExample.setIdCard2Url(userApprove.getIdCard2Url());
            ShopExample.setAddTime(LocalDateTime.now());
            ShopExample.setUpdateTime(LocalDateTime.now());
            //新建商户
            shopService.insertSelective(ShopExample);
            user.setShopId(ShopExample.getId());
            user.setMainUser((byte) 1);
        }else if(user.getMainUser().equals((byte)1)){//判断用户是否为MainUser
            ShopExample = shopService.findById(user.getShopId());
            ShopExample.setContactName(userApprove.getContactName());
            ShopExample.setContactTel(userApprove.getContactTel());
            ShopExample.setContactAddress(userApprove.getContactAddress());
            ShopExample.setUserType(userApprove.getUserType());
            ShopExample.setCompanyName(userApprove.getCompanyName());
            ShopExample.setCompanyLogo(userApprove.getCompanyLogo());
            ShopExample.setCertificatesImage(userApprove.getCertificatesImage());
            ShopExample.setIdCard1Url(userApprove.getIdCard1Url());
            ShopExample.setIdCard2Url(userApprove.getIdCard2Url());
            ShopExample.setUpdateTime(LocalDateTime.now());
            //修改商户
            shopService.updateById(ShopExample);

            List<LitemallUserHerbAuth> userHerbApproveList = userHerbAuthService.queryList(ShopExample.getId().toString());
            for (LitemallUserHerbAuth userHerbApprove:userHerbApproveList) {
                userHerbAuthService.delete(userHerbApprove);
            }
        }


        for (LitemallUserHerbApproveItem userHerbApprove:userAuditService.queryHerbList(userApprove.getId().toString())) {
            userAuditService.delete(userHerbApprove);
        }
        for (String herbGenericName:userApprove.getNewHerbList()) {
            LitemallUserHerbApproveItem userHerbApproveItem = new LitemallUserHerbApproveItem();
            userHerbApproveItem.setHerbGenericName(herbGenericName);
            userHerbApproveItem.setUserApproveId(userApprove.getId());
            userApproveItemService.add(userHerbApproveItem);
        }


//        litemall_user_herb_auth
            for (String herbGenericName:userApprove.getNewHerbList()) {
                LitemallUserHerbAuth userHerbAuth = new LitemallUserHerbAuth();
                userHerbAuth.setHerbGenericName(herbGenericName);
                userHerbAuth.setShopId(ShopExample.getId());
                userHerbAuthService.add(userHerbAuth);
            }

        //admin
//        String username = userApprove.getAdminUsername();
//        String rawPassword = userApprove.getAdminPassword();
//        if(userApprove.getUserType()!=(byte)0){
//            List<LitemallAdmin> adminList = adminService.findAdmin(username);
//            if (adminList.size() > 0 && !adminList.get(0).getId().equals(user.getAdminId())) {
//            throw new RuntimeException("admin账号已经存在");
//        }
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        String encodedPassword = encoder.encode(rawPassword);
//
//        String[] roleId = userApprove.getAdminRoleIds().split(",");
//        Integer[] roleIds = (Integer[]) ConvertUtils.convert(roleId, Integer.class);
//
//        if (StringUtils.isEmpty(user.getAdminId())) {//判断是否有adminId
//            LitemallAdmin admin = new LitemallAdmin();
//            admin.setUsername(username);
//            admin.setPassword(encodedPassword);
//            admin.setShopId(ShopExample.getId());
//            admin.setRoleIds(roleIds);
//            adminService.add(admin);
//            adminList = adminService.findAdmin(username);
//            user.setAdminId(adminList.get(0).getId());
//        }else{
//            LitemallAdmin admin = adminService.findById(user.getAdminId());
//            admin.setUsername(username);
//            admin.setPassword(encodedPassword);
//            admin.setShopId(ShopExample.getId());
//            admin.setRoleIds(roleIds);
//            adminService.updateById(admin);
//        }
//        }
        //user
//        user.setAdminUsername(username);
//        user.setAdminPassword(rawPassword);
        user.setAuthStatus((byte) 1);
        user.setAuthTime(LocalDateTime.now());
        user.setAuthId(userApprove.getId());
        userService.updateById(user);

        //userApprove
        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin loginAdmin = (LitemallAdmin) currentUser.getPrincipal();
        userApprove.setApproveStatus((byte) 1);
        userApprove.setApproveUserId(loginAdmin.getId());
        userApprove.setApproveTime(LocalDateTime.now());
        userAuditService.updateById(userApprove);

        //商户认证类型改变，更新微信端用户数据，使当前商户下的所有微信用户token失效
        userTokenHelper.updateUserToken(user.getShopId());
//        发送微信通知
//        wxSendMessage.pushOneUser(user.getWeixinOpenid(),true);
        return ResponseUtil.ok(wxSendMessage.pushAudit(user.getWeixinOpenid(),"注册信息审核",true,userApprove.getApproveRemark()));
    }


    /**
     * 驳回审批
     *
     * @param userApprove
     * @return
     */
    @RequiresPermissions("admin:userAudit:rejectedUserAudit")
    @RequiresPermissionsDesc(menu = {"信息审批", "用户信息审批"}, button = "驳回审批")
    @PostMapping("/rejectedUserAudit")
    @Transactional(rollbackFor=Exception.class)
    public Object rejectedUserAudit(@RequestBody LitemallUserApprove userApprove) {
        LitemallUser user=userService.findById(userApprove.getUserId());
        Subject currentUser = SecurityUtils.getSubject();
        LitemallAdmin loginAdmin = (LitemallAdmin) currentUser.getPrincipal();
        userApprove.setApproveStatus((byte) 2);
        userApprove.setApproveUserId(loginAdmin.getId());
        userApprove.setApproveTime(LocalDateTime.now());
        userAuditService.updateById(userApprove);
        wxSendMessage.pushAudit(user.getWeixinOpenid(),"注册信息审核",false,userApprove.getApproveRemark());
        return ResponseUtil.ok(userApprove);
    }


}
